#!/bin/bash

# calculate the size of a window that takes exactly half the screen
# excluding decorations (frame extents).
# net_frame_extents is a little C prog I hacked to get those
# (it needs to create a window to measure its dimensions)

# dependencies
deps=(pidof sed net_frame_extents xprop)
for dep in "${deps[@]}"; do
	type -f $dep >/dev/null || __fail__ "Dependency $dep not found."
done
unset dep deps

# Wait for this panel to show up
panel="tint2"

timeout=100 # tenths of s

[ -z "$DISPLAY" ] && { echo "DISPLAY not set. Is Xorg running?"; exit 1; }
if ! pidof "$panel" 1>&2; then
    >&2 echo -n "Waiting for $panel"
    until ((timeout <= 0)); do sleep 0.1; pidof "$panel" 1>&2 && break || { >&2 echo -n '.';  ((timeout--)); }; done
    >&2 echo
fi

(( timeout > 0 )) && {
    sleep 1
    read left right top bottom <<<"$(net_frame_extents  | sed 's/^.*= //; s/,//g')"
    read discard discard width height discard <<<"$(xprop -notype -root _NET_WORKAREA| sed 's/^.*= //; s/,//g')"
    re='^[0-9]+$' # make sure they're all unsigned integers
    if [[ "$left" =~ $re && "$right" =~ $re && "$width" =~ $re && "$top" =~ $re && "$bottom" =~ $re && "$height" =~ $re ]]; then
        printf 'export FRAME_EXTENTS=%s,%s,%s,%s\n' "$left" "$right" "$top" "$bottom"
        halfscreen_w="$(( width/2 - left - right ))"
        printf 'export HALFSCREEN_WIDTH=%s\n' "$halfscreen_w"
        halfscreen_h="$(( height - top - bottom ))"
        printf 'export HALFSCREEN_HEIGHT=%s\n' "$halfscreen_h"
        type -f xmlstarlet openbox 1>&2 && (( halfscreen_w > 0 )) && {
            obrc="$HOME/.config/openbox/rc.xml"
            >&2 echo "Patching $obrc with new width & height"
            # priceless piece of information: https://superuser.com/a/508143
            xmlstarlet ed -L -N o="http://openbox.org/3.4/rc" \
            -u "/o:openbox_config/o:applications/o:application[@class=\"Halfscreen\" or @name=\"Halfscreen\"]/o:size/o:width" \
            -v "$halfscreen_w" \
            -u "/o:openbox_config/o:applications/o:application[@class=\"Halfscreen\" or @name=\"Halfscreen\"]/o:size/o:height" \
            -v "$halfscreen_h" \
            "$obrc" 1>&2 || { >&2 echo "Something went wrong."; exit 1; }
            >&2 echo "Reconfiguring openbox"
            pidof openbox 1>&2 && openbox --reconfigure
        }
    else
        >&2 echo "Got invalid numbers querying extents."; exit 1
    fi
} || { >&2 echo "Panel $panel does not appear to be running"; exit 1; }
